﻿using System.Diagnostics;

namespace NanoMvvm
{
    public class WorkspaceViewModel : PropertyObservableBase, IWorkspace
    {
        private bool isActive;

        public bool IsActive
        {
            get
            {
                return isActive;
            }

            set
            {
                if (value == isActive)
                {
                    return;
                }

                if (value)
                {
                    Activate();
                }
                else
                {
                    Deactivate();
                }
            }
        }

        public void Activate()
        {
            OnActivation();

            if (SetProperty(ref isActive, true, () => IsActive))
            {
                ActivationInternal();
            }
        }

        public bool Deactivate()
        {
            if (isActive == false)
            {
                return true;
            }
            
            if (!PreProcessDeactivation())
            {
                return false;
            }

            OnDeactivation();

            SetProperty(ref isActive, false, () => IsActive);

            DeactivationInternal();

            return true;
        }

        internal void ActivationInternal()
        {
            WorkspaceService.WorkspaceActivated(this);

            OnActivated();
        }

        internal void DeactivationInternal()
        {
            WorkspaceService.WorkspaceDeactivated(this);

            OnDeactivated();
        }

        internal void SetDeactivatedInternal()
        {
            SetProperty(ref isActive, false, () => IsActive);
        }

        protected internal virtual bool PreProcessDeactivation()
        {
            return true;
        }

        protected virtual void OnActivated()
        {
        }

        protected virtual void OnActivation()
        {
        }

        protected virtual void OnDeactivated()
        {
        }

        protected virtual void OnDeactivation()
        {
        }
    }
}